package cn.pconline.autoclub.service;

import cn.pconline.autoclub.entity.ClubVisitor;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.util.Pager;
import java.util.Collections;
import java.util.List;
import org.gelivable.dao.GeliDao;
import org.gelivable.dao.GeliOrm;
import org.gelivable.dao.SqlBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;

/**
 *
 * @author ppc
 */
public class ClubVisitorService {

    @Autowired
    private GeliDao geliDao;
    @Autowired
    private GeliOrm geliOrm;
    @Autowired
    private PagerService pagerService;
    /**
     * 创建访问记录
     *
     * @param clubVisitor
     * @return
     */
    public int createOrUpdateVisitor(ClubVisitor clubVisitor) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql("insert into ").appendSql(geliOrm.getTableName(ClubVisitor.class)).appendSql(" ( club_id,user_id,visitor_date,create_at ) values(").appendValue(clubVisitor.getClubId()).appendSql(",")
                .appendValue(clubVisitor.getUserId()).appendSql(",")
                .appendValue(clubVisitor.getVisitorDate()).appendSql(",")
                .appendValue(clubVisitor.getCreateAt()).appendSql(" ) ON DUPLICATE KEY UPDATE visitor_date = ").appendValue(clubVisitor.getVisitorDate());
        return geliDao.getJdbcTemplate().update(sql.getSql(), sql.getValues());
    }
    
    /**
     * 获取前N个访客
     *
     * @param clubId
     * @param num
     * @return
     */
    public List<User> getVisitorByClubId(long clubId, int num) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql("select user_id from ").appendSql(geliOrm.getTableName(ClubVisitor.class));
        sql.appendSql(" where club_id = ").appendValue(clubId).appendSql(" order by visitor_date desc");
        try {
            return geliDao.page(User.class, sql.getSql(), 1, num, sql.getValues());
        } catch (EmptyResultDataAccessException e) {
            return Collections.emptyList();
        }
    }
    /**
     * 分页获取访客记录
     * @param clubId
     * @param pageNo
     * @param pageSize
     * @return 
     */
    public Pager<ClubVisitor> listVisitorByClubId(long clubId,int pageNo,int pageSize){
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql("select * from ").appendSql(geliOrm.getTableName(ClubVisitor.class)).appendSql("where club_id=").appendValue(clubId).appendSql(" order by visitor_date desc");
        return pagerService.pager(ClubVisitor.class, sql, pageNo, pageSize);
    } 
}
